package cn.itcast.Rainbow_self_mention.Activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import RJZ.Rainbow.UserServer.entity.MapEntity;
import cn.itcast.Rainbow_self_mention.R;
import cn.itcast.Rainbow_self_mention.Server.MapServer;
import cn.itcast.Rainbow_self_mention.Dao.SqlHelper;

public class Map extends AppCompatActivity {
    ListView lv;
    public ImageView home, order, lowmap, mine;
    ImageView flush;
    TextView tv;
    List<MapEntity>mapEntities;
    MyServiceConn conn;
    static MapServer.sender sender;
    AlertDialog dialog;
    RelativeLayout all;
    SqlHelper hp = new SqlHelper(this);
    adapter ad = new adapter();
    static String sentresult;
    static int i = 1;
    static boolean link = false;
    private Timer timer_for_message;

    class MyServiceConn implements ServiceConnection { //用于实现连接服务
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            sender = (MapServer.sender) service;
            sender.getnow();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.low_location);


    }

    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            onResume();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        boolean isopengps;

        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isopengps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        String[] permissions = new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        List<String> mPermissionList = new ArrayList<>();
        int mRequestCode = 100;
        mPermissionList.clear();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        if (mPermissionList.size() > 0) {
            ActivityCompat.requestPermissions(this, permissions, mRequestCode);
        } else if (!isopengps) {
            new AlertDialog.Builder(this).setTitle("open GPS")
                    .setMessage("go to open")
                    //  取消选项
                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Toast.makeText(Map.this, "close", Toast.LENGTH_SHORT).show();
                            // 关闭dialog
                            dialogInterface.dismiss();
                        }
                    })
                    //  确认选项
                    .setPositiveButton("setting", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //跳转到手机原生设置页面
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 1);

                        }
                    })
                    .setCancelable(false)
                    .show();

        } else {
            setContentView(R.layout.low_location);
            Intent server = new Intent(this, MapServer.class);//创建意图对象
            conn = new MyServiceConn();//创建服务连接对象
            bindService(server, conn, BIND_AUTO_CREATE);
            addTimer2();
        }
        init();
        initnutton();
    }

    public void init() {
        home = findViewById(R.id.map_homgpage);
        order = findViewById(R.id.map_deposit);
        lowmap = findViewById(R.id.map_map);
        mine = findViewById(R.id.map_my);
        lv = findViewById(R.id.listview);
        flush = findViewById(R.id.flush);
        tv=findViewById(R.id.map_name);
        initsource();

    }

    public void initsource() {
        SQLiteDatabase db;
        db = hp.getReadableDatabase();
        Cursor cursor = db.query("box", new String[]{"box_id", "location", "longitude", "lantitude", "distance"},
                null, null, null, null, null);
        cursor.moveToFirst();
        int num = cursor.getCount();
        mapEntities=new LinkedList<>();
        if (num > 0) {
            Log.i("活动当前柜子数量", num + "");
            for (int i = 0; i < num; i++) {
                MapEntity mapEntity=new MapEntity(cursor.getString(cursor.getColumnIndex("location")),
                        cursor.getInt(cursor.getColumnIndex("box_id")),
                        cursor.getDouble(cursor.getColumnIndex("longitude")),
                        cursor.getDouble(cursor.getColumnIndex("lantitude")),
                        cursor.getDouble(cursor.getColumnIndex("distance"))
                        );
                mapEntities.add(mapEntity);
                cursor.moveToNext();
            }
            db.close();
            cursor.close();
            initalllistview();
        } else {

        }
    }

    public void initalllistview() {
        if (mapEntities.size() > 0) {
            ad.SetListview(lv);
            ad.SetOnclicklistener(lv);

        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    class adapter extends BaseAdapter {
        public ViewHolder holder;


        public void SetOnclicklistener(ListView lv) {
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    sender.getnow();
                    NaviParaOption para = new NaviParaOption();
                    para.startPoint(new LatLng(sender.ny, sender.nx));
                    para.endPoint(new LatLng(mapEntities.get(position).getLantitude(), mapEntities.get(position).getLontitute()));
                    try {
                        BaiduMapNavigation.openBaiduMapBikeNavi(para, Map.this);
                    } catch (BaiduMapAppNotSupportNaviException e) {
                        e.printStackTrace();
                        Toast.makeText(Map.this, "您尚未安装百度地图app", Toast.LENGTH_SHORT).show();
                    }


                }
            });
        }

        public void SetListview(ListView lv) {
            lv.setAdapter(this);
        }

        @Override
        public int getCount() {
            return mapEntities.size();
        }

        public Object getItem(int position) {
            return mapEntities.get(position).getTitle();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {

                convertView = View.inflate(Map.this, R.layout.item_of_map, null);

                holder = new ViewHolder();
                holder.Title = (TextView) convertView.findViewById(R.id.title);
                holder.Range = (TextView) convertView.findViewById(R.id.range);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.Title.setText(mapEntities.get(position).getTitle());
            holder.Range.setText(mapEntities.get(position).getDistance() + "米");
            holder.Lon = mapEntities.get(position).getLontitute();
            holder.lan = mapEntities.get(position).getLantitude();
            return convertView;
        }
    }

    static class ViewHolder {

        TextView Title;
        TextView Range;
        Double Lon;
        Double lan;

    }

    public void initnutton() {
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Map.this, Home.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Map.this, Order.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        lowmap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sender.get();
                onStart();
            }
        });
        mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Map.this, Personal.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
        flush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(link){
                sender.get();
                unbindService(conn);
                onResume();}
                else {
                    sender.relink();
                }

            }
        });
    }

    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isFinishing()) {
            unbindService(conn);
        }
    }

    public void addTimer2() {
        if (timer_for_message == null) {
            timer_for_message = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    Looper.prepare();
                    if (link) {
                        switch (i) {
                            case 1: {
                                all = new RelativeLayout(Map.this);

                                AlertDialog.Builder builder;
                                TextView t = new TextView(Map.this);
                                t.setText("正在获取位置信息");
                                t.setTextSize(40);
                                RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                                        , RelativeLayout.LayoutParams.WRAP_CONTENT);
                                params2.addRule(RelativeLayout.CENTER_IN_PARENT);
                                all.addView(t, params2);

                                builder = new AlertDialog.Builder(Map.this).setView(all);
                                dialog = builder.create();
                                dialog.show();

                            }
                        }
                    } else {
                        all = new RelativeLayout(Map.this);

                        AlertDialog.Builder builder;
                        TextView t = new TextView(Map.this);
                        t.setText("网络连接失败");
                        t.setTextSize(40);
                        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                                , RelativeLayout.LayoutParams.WRAP_CONTENT);
                        params2.addRule(RelativeLayout.CENTER_IN_PARENT);
                        all.addView(t, params2);

                        builder = new AlertDialog.Builder(Map.this).setView(all);
                        dialog = builder.create();
                        dialog.show();
                        sender.relink();

                    }
                    Looper.loop();
                }
            };
            //开始计时任务后的5毫秒，第一次执行task任务，以后每500毫秒执行一次
            timer_for_message.schedule(task, 1000, 500);
        }

    }

    public static Handler handler = new Handler() {//创建消息处理器对象
        //在主线程中处理从子线程发送过来的消息
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            sentresult = bundle.getString("sentresult");

            //Log.i("sentresult=",sentresult);
            if (sentresult.equals("35")) {
                link = false;//联网失败
            }
            if (sentresult.equals("34")) {
                link = true;//联网成功
            }
            if (sentresult.equals("1")) {
                i = 1;//正在获取
            }
            if (sentresult.equals("2")) {
                i = 2;//获取完成
            }

        }
    };
}
